﻿using System.Web.Mvc;
using System.Web.Security;
using prjYan.Forum.Controllers;

namespace prjYan.Forum.Areas.Admin.Controllers
{
    [Authorize]
    public class PostController : BaseController
    {
        //
        private static int PageSize = 20;
        // GET: /Admin/Post/

        public ActionResult Index(YanForum.Engine.ViewModels.PostOtions options, int page = 1)
        {
            if (!User.IsInRole(YanForum.Engine.ViewModels.UserRoles.Admin)) options.UserId = GetUserId;
            options.PageSize = PageSize;
            options.PageIndex = page;

            var model = YanForum.Engine.Services.Post.SearchPost(options);

            return View(model);
        }

        public ActionResult Update(int? id)
        {
            id = id != null ? id : 0;
            var model = YanForum.Engine.Services.Post.GetPostById(id.Value);

            if (id != 0 && model.Title == null)
            {
                return RedirectToAction("Index");
            }

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        //[ValidateAntiForgeryToken]
        public ActionResult Update(YanForum.Engine.ViewModels.PostUpdate model)
        {
            if (ModelState.IsValid)
            {
                //CheckNull
                if (!string.IsNullOrEmpty(model.ImagePath) && model.ImagePath != "/")
                {
                    model.ThumbFolder = model.ImagePath.Substring(0, 6);
                    model.ThumbName = model.ImagePath.Substring(7);
                }
                else
                {
                    model.ThumbFolder = "";
                    model.ThumbName = "";
                }
                ViewBag.Success = "Đã cập nhật thành công.";
                model.UserId = GetUserId;
                //Store Update
                YanForum.Engine.Services.Post.UpdatePost(model);

                return View(model);
            }
            return View(model);
        }

        public JsonResult AjaxDeletePost(int postId)
        {
            var _post = YanForum.Engine.Services.Post.GetPostById(postId);

            if(_post.Title == null)
                return Json(new { status = false, message = "Không tìm thấy bài viết." });

            if (!User.IsInRole(YanForum.Engine.ViewModels.UserRoles.Admin) && _post.UserId != GetUserId)
                return Json(new { status = false, message = "Bạn không có quyền xóa bài viết." });

            var _delete = YanForum.Engine.Services.Post.DeletePost(postId);

            if (_delete)
                return Json(new { status = true });
            else
                return Json(new { status = false, message = "Có lỗi xảy ra."});
        }
    }
}
